import React, { Component } from 'react';
import { Text, Image, View, DeviceEventEmitter, TouchableOpacity, ScrollView, NativeAppEventEmitter } from 'react-native';
import { unitWidth, width } from '../constants/AdapterUtil';
import { MyHeader } from '../components/MyHeader';
import Colors from '../constants/Colors';
import { postFetch } from '../constants/HttpExtension';
import { show } from '../constants/Toast';
import { api_member_info_Certification, api_member_info_companyRealname, ORDER_WORKORDER_TAX, api_order_workorder_submit, api_member_address } from '../constants/HttpServices';
import { SubmitButton1 } from '../components/Button';
import { MyInput1, MyInput2 } from '../components/Input';
import TextUtil from '../constants/TextUtil';
import { ChooseSingleImageItem, ChooseMultiplyImageItem, TextItem, ChooseTimeItem, ReleaseComponentItem, Item1 } from '../components/Item';
import { LoadingAndPorgressModal, CommonModal3, BottomShareModal, BottomAddressChooseModal } from '../components/Modal';
import { uploadFile } from '../constants/UpLoadHelper';
import TimePickerUtil from '../components/TimePicker';
import DateUtil from '../constants/DateUtil';

export default class ReleaseDemandScreen extends Component {

    constructor(props) {
        super(props)

        const { navigation } = this.props;
        this.state = {
            title: '',//标题
            general_budget: '',//总预算
            end_date: '',//截止日期
            delivery_date: '',//交货日期
            mobile: '',//联系电话
            pay_type: '1',//支付方式 1=平台支付，2=线下对接
            other: '1',//其他选项 1=含运费 2=不含运费 3=管家配送
            address: '',//收货地址
            remark: '',//补充说明
            file: [],//附件，多图片字符串数组
            element: '',//零件信息
            province: '',//省
            city: '',//市
            area: '',//区
            receiver_name: '',//收货联系人
            receiver_mobile: '',//收货联系方式

            addressList: [],
            currentChooseAddressIndex: 0,

            //以上是最后要传上去的
            //零件信息格式
            // {
            //     “name”: “测试1”,
            //     “count”: 1,
            //     “money”: 100,
            //     “remark”: “项目说明1”,
            //     “img”: [
            //     “http://a806.mxnt.net/attachment/images/1/2019/10/NFzK1U88NpXOokuyyypXK9Bb16Pa81.png“,
            //     “http://a806.mxnt.net/attachment/images/1/2019/10/NFzK1U88NpXOokuyyypXK9Bb16Pa81.png“
            //     ]
            //     },

            oneCate: {},
            twoCate: {},
            threeCate: {},
            money: 0,
            fileImageList: [],
            elementList: [],//零部件信息列表
            elementCount: 1,

            progress: '0%',
            tax: 1,
        }
    }

    componentDidMount() {
        this.props.navigation.addListener('didFocus', payload => {
            this.getAddress()
        })
        this.getWORKORDER();
    }

    componentWillUnmount() {
        if (TimePickerUtil.myPicker) {
            TimePickerUtil.myPicker.hide();
        }
    };

    changeMoney() {
        this.state.money = 0
        for (let key in this.elementRefs) {
            let item = this.elementRefs[key];
            this.state.money += parseFloat(item.state.money)
        }
        console.log(this.state.money)
        // if (global.userInfo.id_type == '2') {
        //     this.setState({
        //         // money: Math.round(this.state.money * 1.17)
        //         money: Math.round(this.state.money)
        //     })
        // } else {
        let tax = this.state.tax * 1000

        console.log(tax)
        this.state.money = this.state.money * tax
        this.setState({
            money: this.state.money / 1000
        })
        // }
    }

    getElementView() {
        this.elementViews = [];
        this.elementRefs = [];
        for (let i = 0; i < this.state.elementCount; i++) {
            this.elementViews.push(
                <ReleaseComponentItem
                    ref={(v) => {
                        this.elementRefs[`element${i}`] = v;
                    }} count={i + 1}
                    onMoneyChange={() => { this.changeMoney(); }} />
            );
        }
        return this.elementViews
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF5 }}>
                <MyHeader title='发布需求' leftImg={require('../res/ic_arrow_left.png')} leftClick={() => { this.props.navigation.pop() }} />
                <ScrollView style={{ flex: 1 }} showsVerticalScrollIndicator={false}>
                    <View>
                        <View style={{ backgroundColor: Colors.white }}>
                            <TextItem titleStyle={{ fontWeight: 'bold', fontSize: 16 }} title='基本信息' />
                            <MyInput1
                                style={{ marginTop: 0 * unitWidth }}
                                onChangeText={(text) => { this.setState({ title: text }) }}
                                title={
                                    <Text style={{ color: Colors.black, fontSize: 15 }}>询价标题：</Text>
                                }
                                maxLength={100}
                                placeholder='请输入询价标题'
                                value={this.state.title} isLast={false} />
                            <Item1 title='询价类目：'
                                value={this.state.oneCate.name ? (this.state.oneCate.name + '   ' + (this.state.twoCate ? this.state.twoCate.name + '   ' : '')
                                    + (this.state.threeCate ? this.state.threeCate.name : '')) : ''}
                                tips='请选择询价类目'
                                onPress={() => {
                                    this.props.navigation.navigate('ChooseCate', {
                                        onChooseSuccess: (oneCate, twoCate, threeCate) => {
                                            console.log(oneCate)
                                            console.log(twoCate)
                                            console.log(threeCate)
                                            this.setState({
                                                oneCate: oneCate,
                                                twoCate: twoCate,
                                                threeCate: threeCate
                                            })
                                        }
                                    })
                                }} />
                            {/* <MyInput1
                                style={{ marginTop: 0 * unitWidth }}
                                onChangeText={(text) => { this.setState({ general_budget: text }) }}
                                filterType={2}
                                title={
                                    <Text style={{ color: Colors.black, fontSize: 15 }}>总预算(含税)：</Text>
                                }
                                maxLength={100}
                                placeholder='请输入总预算，精确到小数点后两位'
                                value={this.state.general_budget} isLast={false} /> */}
                            <ChooseTimeItem
                                title='截止日期：'
                                tips='请选择截至日期'
                                time={this.state.end_date}
                                onChooseSuccess={(data) => {
                                    this.setState({
                                        end_date: data
                                    })
                                }} />
                            <ChooseTimeItem
                                title='交货日期：'
                                tips='请选择交货日期'
                                time={this.state.delivery_date}
                                onChooseSuccess={(data) => {
                                    this.setState({
                                        delivery_date: data
                                    })
                                }} />
                            <MyInput1
                                style={{ marginTop: 0 * unitWidth }}
                                onChangeText={(text) => { this.setState({ mobile: text }) }}
                                filterType={1}
                                title={
                                    <Text style={{ color: Colors.black, fontSize: 15 }}>联系电话：</Text>
                                }
                                maxLength={11}
                                placeholder='请输入联系电话'
                                value={this.state.mobile} isLast={false} />
                            <Item1 title='收货地址：'
                                value={this.state.address ? (this.state.address + '     ' + this.state.receiver_name + '     ' + this.state.receiver_mobile) : ''} tips='请添加收货地址'
                                onPress={() => {
                                    // this.props.navigation.navigate('AddAddress', {
                                    //     onSuccess: (data) => {
                                    //         this.setState({
                                    //             address: data.address,
                                    //             receiver_mobile: data.mobile,
                                    //             receiver_name: data.name,
                                    //             province: data.province,
                                    //             city: data.city,
                                    //             area: data.area,
                                    //         })
                                    //     },
                                    //     data: {
                                    //         address: this.state.address,
                                    //         receiver_mobile: this.state.receiver_mobile,
                                    //         receiver_name: this.state.receiver_name,
                                    //         province: this.state.province,
                                    //         city: this.state.city,
                                    //         area: this.state.area,
                                    //     }
                                    // })
                                    this.refs.BottomAddressChooseModal.showModal();
                                }} />
                        </View>
                        <View style={{ backgroundColor: Colors.white, marginTop: 5 * unitWidth }}>
                            <View style={{}}>
                                <View style={{
                                    width: width, minHeight: 50 * unitWidth, flexDirection: 'row', paddingHorizontal: 20 * unitWidth,
                                    backgroundColor: Colors.white, alignItems: 'flex-start', paddingVertical: 15 * unitWidth, justifyContent: 'space-between'
                                }}>
                                    <View style={{ alignItems: 'flex-start', justifyContent: 'flex-start' }}>
                                        <Text style={{ color: Colors.black, fontSize: 16, fontWeight: 'bold' }}>零部件信息</Text>
                                    </View>
                                    <TouchableOpacity activeOpacity={0.7} onPress={() => { this.setState({ elementCount: this.state.elementCount + 1 }) }}>
                                        <Image style={{ width: 18 * unitWidth, height: 18 * unitWidth }} source={require('../res/fbxq_add.png')} resizeMode='stretch' />
                                    </TouchableOpacity>
                                </View>
                                <View style={{ backgroundColor: Colors.colorEF, width: width, alignSelf: 'center', height: 0.5, marginTop: 10 * unitWidth, position: 'absolute', bottom: 0 }} />
                            </View>
                            {this.getElementView()}
                            <View style={{ height: 40 * unitWidth, backgroundColor: Colors.white, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', paddingHorizontal: 20 * unitWidth }}>
                                <Text style={{ fontSize: 15, color: Colors.colorOrange }}>合计：<Text style={{ fontSize: 20 }}>￥{this.state.money}</Text></Text>
                            </View>
                        </View>
                        <View style={{ backgroundColor: Colors.white, marginTop: 5 * unitWidth }}>
                            <TextItem titleStyle={{ fontWeight: 'bold', fontSize: 16 }} title='支付方式' />
                            <View style={{ backgroundColor: Colors.white, height: 40 * unitWidth, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                <TouchableOpacity activeOpacity={0.7} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', flex: 1, }}
                                    onPress={() => { this.setState({ pay_type: '1' }) }}>
                                    <Image style={{ width: 18 * unitWidth, height: 18 * unitWidth }} resizeMode='stretch'
                                        source={this.state.pay_type == '1' ? require('../res/ic_choose_c.png') : require('../res/ic_choose_n.png')} />
                                    <Text style={{ fontSize: 15, color: Colors.black, marginLeft: 5 * unitWidth }}>平台支付</Text>
                                </TouchableOpacity>
                                <TouchableOpacity activeOpacity={0.7} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', flex: 1, }}
                                    onPress={() => { this.setState({ pay_type: '2' }) }}>
                                    <Image style={{ width: 18 * unitWidth, height: 18 * unitWidth }} resizeMode='stretch'
                                        source={this.state.pay_type == '2' ? require('../res/ic_choose_c.png') : require('../res/ic_choose_n.png')} />
                                    <Text style={{ fontSize: 15, color: Colors.black, marginLeft: 5 * unitWidth }}>线下对接</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                        <View style={{ backgroundColor: Colors.white, marginTop: 5 * unitWidth }}>
                            <TextItem titleStyle={{ fontWeight: 'bold', fontSize: 16 }} title='其他选项' />
                            <View style={{ backgroundColor: Colors.white, height: 50 * unitWidth, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', flex: 1.5, }}>
                                    <Text style={{ fontSize: 15, color: Colors.black, marginLeft: 5 * unitWidth }}>送货免费供应商</Text>
                                </View>
                                <TouchableOpacity activeOpacity={0.7} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', flex: 1, }}
                                    onPress={() => { this.setState({ other: '1' }) }}>
                                    <Image style={{ width: 13 * unitWidth, height: 13 * unitWidth }} resizeMode='stretch'
                                        source={this.state.other == '1' ? require('../res/me_wsxxyd1.png') : require('../res/me_wsxxyd2.png')} />
                                    <Text style={{ fontSize: 13, color: Colors.black, marginLeft: 5 * unitWidth }}>含运费</Text>
                                </TouchableOpacity>
                                <TouchableOpacity activeOpacity={0.7} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', flex: 1, }}
                                    onPress={() => { this.setState({ other: '2' }) }}>
                                    <Image style={{ width: 13 * unitWidth, height: 13 * unitWidth }} resizeMode='stretch'
                                        source={this.state.other == '2' ? require('../res/me_wsxxyd1.png') : require('../res/me_wsxxyd2.png')} />
                                    <Text style={{ fontSize: 13, color: Colors.black, marginLeft: 5 * unitWidth }}>不含运费</Text>
                                </TouchableOpacity>
                                <TouchableOpacity activeOpacity={0.7} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', flex: 1, }}
                                    onPress={() => { this.setState({ other: '3' }) }}>
                                    <Image style={{ width: 13 * unitWidth, height: 13 * unitWidth }} resizeMode='stretch'
                                        source={this.state.other == '3' ? require('../res/me_wsxxyd1.png') : require('../res/me_wsxxyd2.png')} />
                                    <Text style={{ fontSize: 13, color: Colors.black, marginLeft: 5 * unitWidth }}>管家配送</Text>
                                </TouchableOpacity>
                            </View>
                            <View style={{ backgroundColor: Colors.colorEF, width: width, alignSelf: 'center', height: 0.5 }} />
                            <MyInput1
                                style={{ marginTop: 0 * unitWidth }}
                                onChangeText={(text) => { this.setState({ remark: text }) }}
                                title={
                                    <Text style={{ color: Colors.black, fontSize: 15 }}>补充说明：</Text>
                                }
                                maxLength={100}
                                placeholder='请补充说明'
                                value={this.state.remark} isLast={false} />
                            <ChooseMultiplyImageItem
                                style={{}}
                                title='附件'
                                ImageList={this.state.fileImageList}
                                onDeletePress={(index) => {
                                    this.state.fileImageList.splice(index, 1);
                                    this.setState({
                                        fileImageList: this.state.fileImageList
                                    })
                                }}
                                onChooseSuccess={(selectedPhotos) => {
                                    this.setState({
                                        fileImageList: [...this.state.fileImageList, ...selectedPhotos]
                                    })
                                }}
                                isLast={false} />
                        </View>
                        <SubmitButton1 style={{ marginVertical: 38 * unitWidth, alignSelf: 'center' }} text='立即发布' onPress={() => {
                            this.doUpload();
                        }} />
                    </View>
                </ScrollView>
                <LoadingAndPorgressModal ref='LoadingAndPorgressModal' progress={this.state.progress} />
                <CommonModal3 ref='CommonModal3' title={'恭喜你发布成功\n请耐心等待'}
                    btnText='分享'
                    onPress={() => {
                        this.refs.CommonModal3.hideModal();
                        this.refs.BottomShareModal.showModal();
                    }}
                    onClosePress={() => {
                        this.props.navigation.pop();
                    }} />
                <BottomShareModal ref='BottomShareModal' leftClick={() => {
                    this.props.navigation.pop();
                }} rightClick={() => {
                    this.props.navigation.pop();
                }} />
                <BottomAddressChooseModal ref='BottomAddressChooseModal'
                    currentChooseAddressIndex={this.state.currentChooseAddressIndex}
                    addressList={this.state.addressList} onChoose={(item, index) => {
                        this.setState({
                            receiver_mobile: item.mobile,
                            receiver_name: item.realname,
                            province: item.province,
                            city: item.city,
                            area: item.area,
                            address: item.address,
                            currentChooseAddressIndex: index,
                        })
                    }} />
            </View>
        );
    }

    doUpload() {
        if (this.state.title == '') {
            show('请输入询价标题');
            return;
        } else if (!this.state.oneCate.name) {
            show('请选择询价类目');
            return;
        } else if (this.state.money == '') {
            show('请输入预算金额');
            return;
        } else if (this.state.end_date == '') {
            show('请选择截止日期');
            return;
        } else if (this.state.delivery_date == '') {
            show('请选择交货日期');
            return;
        } else if (!DateUtil.isAfterDay(this.state.end_date)) {
            show('只能选择今天之后的日期作为截止日期');
            return;
        } else if (!DateUtil.isAfterDay(this.state.delivery_date)) {
            show('只能选择今天之后的日期作为交货日期');
            return;
        } else if (this.state.mobile == '') {
            show('请输入联系电话');
            return;
        } else if (this.state.address == '') {
            show('请输入收货地址');
            return;
        }
        // else if (parseFloat(this.state.money) != parseFloat(this.state.general_budget)) {
        //     show('总预算和合计金额对不上');
        //     return;
        // }

        let ImageList = [];
        let elementInfoList = [];
        for (let key in this.elementRefs) {
            let item = this.elementRefs[key];
            ImageList = [...ImageList, ...item.state.imageList];
            elementInfoList.push(item.state)
        }

        if (this.state.fileImageList && this.state.fileImageList.length > 0) {
            ImageList = [...ImageList, ...this.state.fileImageList]
        }

        if (ImageList && ImageList.length > 0) {
            this.refs.LoadingAndPorgressModal.showModal();
            uploadFile(ImageList, (text) => {
                this.setState({
                    progress: text
                })
            }, {
                success: (response) => {
                    this.refs.LoadingAndPorgressModal.hideModal();

                    let params = []
                    for (let x of elementInfoList) {
                        let tempImage = response.files.splice(0, x.imageList.length);
                        let param = {
                            name: x.name,
                            count: x.count,
                            money: x.money,
                            remark: x.remark,
                            img: [],
                        }
                        for (let y of tempImage) {
                            param.img.push(y.url)
                        }
                        params.push(param)
                    }
                    if (this.state.fileImageList.length > 0) {
                        let tempImage = response.files;
                        this.state.file = []
                        for (let y of tempImage) {
                            this.state.file.push(y.url)
                        }
                    }
                    this.setState({
                        element: JSON.stringify(params),
                        file: this.state.file
                    })

                    this.submit();
                },
                fail: (response) => {
                    this.refs.LoadingAndPorgressModal.hideModal();
                    show('上传失败')
                }
            })
        } else {
            show('请选择零部件信息的图片')
            return;
        }
    }

    submit() {
        let params = {
            title: this.state.title,//标题
            general_budget: this.state.money,//总预算
            end_date: this.state.end_date,//截止日期
            delivery_date: this.state.delivery_date,//交货日期
            mobile: this.state.mobile,//联系电话
            pay_type: this.state.pay_type,//支付方式 1=平台支付，2=线下对接
            other: this.state.other,//其他选项 1=含运费 2=不含运费 3=管家配送
            address: this.state.address,//收货地址
            remark: this.state.remark,//补充说明
            file: JSON.stringify(this.state.file),//附件，多图片字符串数组
            element: this.state.element,//零件信息
            province: this.state.province,//省
            city: this.state.city,//市
            area: this.state.area,//区
            receiver_name: this.state.receiver_name,//收货联系人
            receiver_mobile: this.state.receiver_mobile,//收货联系方式
            one_cate: this.state.oneCate.id,
            two_cate: this.state.twoCate ? this.state.twoCate.id : null,
            three_cate: this.state.threeCate ? this.state.threeCate.id : null,
        }
        postFetch(api_order_workorder_submit, params, {
            success: (response) => {
                // show(response.result.message);
                this.refs.CommonModal3.showModal();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //获取地址
    getAddress() {
        let params = {

        }
        postFetch(api_member_address, params, {
            success: (response) => {

                for (let i = 0, len = response.result.list.length; i < len; i++) {
                    let item = response.result.list[i]
                    if (item.isdefault == '1') {
                        this.setState({
                            addressList: response.result.list,
                            receiver_mobile: item.mobile,
                            receiver_name: item.realname,
                            province: item.province,
                            city: item.city,
                            area: item.area,
                            address: item.address,
                            currentChooseAddressIndex: i
                        })
                        break
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //获取地址
    getWORKORDER() {
        let params = {

        }
        postFetch(ORDER_WORKORDER_TAX, params, {
            success: (response) => {

                this.setState({
                    tax: response.result.tax
                })
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}